/**
 * Copyright (c) 2019-2021,  陈俊兵 (cjb6b.com@gmail.com)
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.ktjiaoyu.advance.threadlocal;

/**
 * ThreadLocal测试
 *
 * @author 陈俊兵 (cjb6b.com@gmail.com)
 * @version 1.0.0
 * @fileName ThreadLocalTest.java
 * @createTime 2020/10/9 20:10
 * @lastModify 2020/10/9 20:10
 */
public class ThreadLocalTest {
    // 存储字符串的线程本地变量
    static ThreadLocal<String> local = new ThreadLocal<String>();

    public static void main(String[] args) {


        Thread t1 = new Thread(() -> {
            try {
                local.set("t1");
                System.out.println("t1线程已经将变量设置到local中");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("t1取出local中的变量" + local.get());
            } finally {
                // 移除数据
                local.remove();
            }
        });

        Thread t2 = new Thread(() -> {
            try {
                local.set("t2");
                System.out.println("t2线程已经将变量设置到local中");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("t2取出local中的变量" + local.get());
            } finally {
                // 移除数据
                local.remove();
            }
        });

        t1.start();
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t2.start();
    }
}
